# -*- coding: utf-8 -*-

"""
jiandan.py：文件名规则变更（怀疑每页的图片都可能在变化）

old: =========================================
filename = '%03d_%03d%s' % (start_page, index, img_ext)
filepath = os.path.join(SAVE_DIR, filename.encode('gbk'))

new: =========================================
filename = img_url.replace('/', '-').encode(sys.getfilesystemencoding())
if img_ext == '.gif':
    filepath = os.path.join(SAVE_DIR, 'gif', filename)
else:
    filepath = os.path.join(SAVE_DIR, filename)
"""

import json
import os
import shutil

import filetype

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(CURRENT_DIR, 'jiandan')
METADATA_FILE = os.path.join(IMG_DIR, 'metadata.json')
METADATA_BACKUP = os.path.join(IMG_DIR, 'old_metadata.json')
if not os.path.exists(METADATA_BACKUP):
    shutil.copy(METADATA_FILE, METADATA_BACKUP)
with open(METADATA_BACKUP) as f:
    METADATA = json.load(f)
NEW_METADATA = []

def rename(img_data):
    if len(img_data) != 3:
        print 'error metadata:', img_data
        return
    url = img_data[0]
    filepath = img_data[1]
    status = img_data[2]
    fullpath = os.path.join(IMG_DIR, filepath)

    path_dir = os.path.dirname(filepath)
    # path_filename = os.path.basename(filepath)

    _, ext = os.path.splitext(url)
    new_name = url.replace('/', '-')
    if ext == '.gif':
        path_dir = os.path.join(path_dir, 'gif', )
    new_fullpath = os.path.join(IMG_DIR, path_dir, new_name)

    if status != 'ok':
        if os.path.exists(fullpath):
            print 'error img:', fullpath, status
    else:
        NEW_METADATA.append([url, os.path.relpath(new_fullpath, IMG_DIR), status])
        if os.path.exists(new_fullpath):
            # print 'has been downloaded:', url
            return

        if not os.path.exists(fullpath):
            # 有可能被 fix_002 改名成 .gif 后缀了
            fullpath = os.path.splitext(fullpath)[0] + '.gif'
            if not os.path.exists(fullpath):
                print 'file not found:', fullpath
                return

        new_path = os.path.dirname(new_fullpath)
        if not os.path.exists(new_path):
            os.makedirs(new_path)

        try:
            print 'rename: %s --> %s' % (fullpath, new_fullpath)
            os.rename(fullpath, new_fullpath)
        except Exception as error:
            print error
            print fullpath, new_fullpath

for i in METADATA:
    rename(i)

with open(METADATA_FILE, 'w') as f:
    json.dump(NEW_METADATA, f, indent=4, ensure_ascii=False)
